package com.anne.fish.webapp.action;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;

import com.anne.fish.Constants;
import com.anne.fish.model.InfoImage;
import com.anne.fish.service.InfoImageManager;
import com.anne.fish.service.img.ImageManager;
import com.anne.fish.webapp.util.DateTimeFormatUtil;
import com.anne.fish.webapp.util.RequestUtil;

/**
 * Sample action that shows how to do file upload with Struts 2.
 */
public class FileUploadAction extends BaseAction {
    private static final long serialVersionUID = -9208910183310010569L;
    private File file;
    private String fileContentType;
    private String fileFileName;
    private String name;
	private String uploadFileName;
	private ImageManager imageManager;
    
	private String Upload;
 

	public void setUpload(String upload) {
		Upload = upload;
	}

	public void setImageManager(ImageManager imageManager) {
		 
		this.imageManager = imageManager;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	 private InfoImageManager infoImageManager;
		public void setInfoImageManager(InfoImageManager infoImageManager) {
			this.infoImageManager = infoImageManager;
		}
	/**
	 * ckeditor
	 * 
	 * @return
	 * @throws Exception
	 */
	public String upload() throws Exception {


		String extend = uploadFileName.substring(uploadFileName.lastIndexOf("."));
		int ranNumber = RequestUtil.getRandom();
		String destFileName = System.currentTimeMillis() + "_" + ranNumber + extend;

		String dir = DateTimeFormatUtil.convertDateToString(new Date(), "yyyyMMdd");
		 
		String localImagePath = Constants.GD_IMAGE_LOCAL_IMAGE_PATH;
		
		String uploadDir = ServletActionContext.getServletContext().getRealPath(localImagePath)+ "/" + dir + "/";
		imageManager.upload(upload, destFileName ,uploadDir);

		
		
		
		String contextPath = getRequest().getContextPath();
		
		String link = contextPath + localImagePath + dir + "/" + destFileName;
		
		getResponse().setContentType("text/html; charset=UTF-8");
		getResponse().setHeader("Cache-Control", "no-cache");
		PrintWriter out = getResponse().getWriter();
		String callback = getRequest().getParameter("CKEditorFuncNum");
		out.println("<script type=\"text/javascript\">");
		out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + link + "',''" + ")");
		out.println("</script>");
		out.flush();
		out.close();
		return null;
	
	 
	}
    
    /**
     * Upload the file
     *
     * @return String with result (cancel, input or sucess)
     * @throws Exception if something goes wrong
     */
    public String uploadFile() throws Exception {
        if (this.cancel != null) {
            return "cancel";
        }

        // the directory to upload to
        String uploadDir = ServletActionContext.getServletContext().getRealPath("/resources")
                + "/" + getRequest().getRemoteUser() + "/";

        // write the file to the file specified
        File dirPath = new File(uploadDir);

        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }

        //retrieve the file data
        InputStream stream = new FileInputStream(file);

        //write the file to the file specified
        OutputStream bos = new FileOutputStream(uploadDir + fileFileName);
        int bytesRead;
        byte[] buffer = new byte[8192];

        while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }

        bos.close();
        stream.close();

        // place the data into the request for retrieval on next page
        getRequest().setAttribute("location", dirPath.getAbsolutePath()
                + Constants.FILE_SEP + fileFileName);

        String link = getRequest().getContextPath() + "/resources" + "/"
                + getRequest().getRemoteUser() + "/";

        getRequest().setAttribute("link", link + fileFileName);

        return SUCCESS;
    }

   

	public String swfUpload() throws Exception {
		HttpServletRequest request = getRequest();
		MultiPartRequestWrapper muti = ((MultiPartRequestWrapper) getRequest());
		String fileName = muti.getParameter("Filename");
		String model = muti.getParameter("Upload");

		String dir = DateTimeFormatUtil.convertDateToString(new Date(), "yyyyMMdd");
		 
		String localImagePath = Constants.GD_IMAGE_LOCAL_IMAGE_PATH;
		
		String uploadDir = ServletActionContext.getServletContext().getRealPath(localImagePath)+ "/" + dir + "/";
		
		
		//boolean isImage = model != null && model.equals("GoodsImages");
		 
			String extend = fileName.substring(fileName.lastIndexOf("."));
			extend = extend.toLowerCase();
			long base = System.currentTimeMillis();
			int ranNumber = RequestUtil.getRandom();
			String b_image_name = base + "_" + ranNumber + extend;

			File file = ((MultiPartRequestWrapper) request).getFiles("file")[0];
			byte[] src_fileData = changeFileToBytes(file);
			imageManager.upload(src_fileData, b_image_name ,uploadDir);
			
			String contextPath = getRequest().getContextPath();			
			String link = contextPath + localImagePath + dir + "/" + b_image_name;
			//
			InfoImage infoImage = new InfoImage();
			infoImage.setBig(link);
			infoImage.setCreateTime(System.currentTimeMillis());
			infoImage.setInfoId(0L);
			infoImage.setSmall(link);
			infoImage.setSource(link);
			infoImage.setSrcSizeHeight(0L);
			infoImage.setSrcSizeWidth(0L);
			infoImage=this.infoImageManager.save(infoImage);
			//
			
			link = link+"__"+infoImage.getId();
			
			
			PrintWriter out = getResponse().getWriter();
			out.println(link);
			out.flush();
			out.close();
		 

		return SUCCESS;
	}
	public static byte[] changeFileToBytes(File file) throws Exception{
		 

		BufferedInputStream bufInputStream = new BufferedInputStream(
				new FileInputStream(file));

		ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

		byte[] bytes = new byte[1000];

		// 将文件内容写入位数组流
		while (bufInputStream.read(bytes) != -1) {
			arrayOutputStream.write(bytes);
		}
		arrayOutputStream.close();
		bufInputStream.close();

		// 以字符方式显示位数组内容
		bytes = arrayOutputStream.toByteArray();
		return bytes;
	}
    
    
    /**
     * Default method - returns "input"
     *
     * @return "input"
     */
    public String execute() {
        return INPUT;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public File getFile() {
        return file;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    private String CKEditorFuncNum;   
            
        public String getCKEditorFuncNum() {
		return CKEditorFuncNum;
	}

	public void setCKEditorFuncNum(String cKEditorFuncNum) {
		CKEditorFuncNum = cKEditorFuncNum;
	}

	public String getCKEditor() {
		return CKEditor;
	}

	public void setCKEditor(String cKEditor) {
		CKEditor = cKEditor;
	}

	private String Type;
	public String getType() {
		return Type;
	}

	public void setType(String type) {
		Type = type;
	}

	public String getLangCode() {
		return langCode;
	}

	public void setLangCode(String langCode) {
		this.langCode = langCode;
	}

		private String CKEditor;   
           
       private String langCode;   
         
    @Override
	public void validate() {
    	HttpServletRequest re = this.getRequest();
		if (re.getMethod().equalsIgnoreCase("post")) {
			getFieldErrors().clear();
			if ("".equals(uploadFileName) || upload == null) {
				//super.addFieldError("upload", getText("errors.requiredField", new String[] { getText("uploadForm.file") }));
			} else if (upload.length() > 2097152) {
				addActionError(getText("maxLengthExceeded"));
			}
			try {
				//swfUpload();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
